package com.zdb;



import org.apache.hc.client5.http.classic.methods.HttpPost;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.ClassicHttpResponse;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class ZhipuFileUploadDemo {

    // 1) 请替换为你的实际 API Key（带 Bearer 前缀）
    private static final String API_KEY = "18c64c7b16d869f86953ade9571c3b87.FVhAx2TS7X7JB04n";

    // 2) 上传用途：file-extract / retrieval / batch / fine-tune ...
    private static final String PURPOSE = "file-extract";

    // 3) 如果 purpose=retrieval，必须指定 knowledge_id；否则可留空
    private static final String KNOWLEDGE_ID = "";   // 例如 "6432c1e93a4e51b1e24b4a44"

    // 4) 本地待上传文件
    private static final String LOCAL_PATH = "D:/desk/源码解析/1111.txt";

    public static void main(String[] args) {
        // --- 0. 文件合法性校验 ---
        File file = new File(LOCAL_PATH);
        if (!file.exists() || !file.isFile()) {
            System.err.println("文件不存在或路径无效：" + LOCAL_PATH);
            return;
        }

        // --- 1. 创建 HttpClient ---
        try ( CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpPost post = new HttpPost("https://open.bigmodel.cn/api/paas/v4/files");
            post.setHeader("Authorization", API_KEY);

            // --- 2. 组装 multipart/form-data ---
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(StandardCharsets.UTF_8);

            // 2.1 普通文本字段
            builder.addTextBody("purpose", PURPOSE, ContentType.TEXT_PLAIN);
            if (!KNOWLEDGE_ID.isEmpty()) {        // 仅在检索上传时需要
                builder.addTextBody("knowledge_id", KNOWLEDGE_ID, ContentType.TEXT_PLAIN);
            }

            // 2.2 二进制文件字段
            builder.addBinaryBody(
                    "file",                       // 字段名必须叫 file
                    file,   
                    ContentType.APPLICATION_OCTET_STREAM,
                    file.getName()               // ★ 不能为 null，否则会触发 NPE
            );

            post.setEntity(builder.build());

            // --- 3. 执行请求 ---
            ClassicHttpResponse response = httpClient.executeOpen(null, post, null);
            int status = response.getCode();
            String body  = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            System.out.println("Status Code = " + status);
            System.out.println("Response    = " + body);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void demo(String message){

    }
}
